# -*- coding:utf-8 -*-
from database import db
from datetime import datetime
from flask.ext.script import Command, Option, prompt_bool
from sqlalchemy.schema import *

import os
import config


class CreateDB(Command):
    """Creates sqlalchemy database"""

    def run(self):
        from database import create_all

        create_all()


class DropDB(Command):
    """Drops sqlalchemy database"""

    def run(self):
        from database import drop_all

        drop_all()


class Test(Command):
    """Run tests."""

    start_discovery_dir = "tests"

    def get_options(self):
        return [
            Option('--start_discover', '-s', dest='start_discovery',
                   help='Pattern to search for features',
                   default=self.start_discovery_dir),
        ]

    def run(self, start_discovery):
        import unittest

        if os.path.exists(start_discovery):
            argv = [config.project_name, "discover"]
            argv += ["-s", start_discovery]

            unittest.main(argv=argv)
        else:
            print("Directory '%s' was not found in project root." % start_discovery)




ROLE_USER = 0
ROLE_ADMIN = 1

class UserPeso(db.Model):
    __tablename__ = 'userpeso'
    
    id = db.Column(db.Integer, primary_key = True)
    timestamp = db.Column(db.Date())
    peso = db.Column(db.SmallInteger)


class UserHistory(db.Model):
    __tablename__ = 'userhistory'
    
    id = db.Column(db.Integer, primary_key = True)
    
    #one to one
    #child = db.relationship("userhistory", uselist=False, backref="user")

    #pesoHistorico = db.relationship("UserPeso")
  
class AuthProvider(db.Model):
	__tablename__ = 'auth_provider'

	id = db.Column(db.Integer, primary_key = True)
	nombre = db.Column(db.String(64))
	image_url = db.Column(db.String(255))
	user = db.relationship("User",backref="users")


class User(db.Model):
    
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key = True)
    apodo = db.Column(db.String(64), index = True, unique = True)
    email = db.Column(db.String(120), index = True, unique = True)
    role = db.Column(db.SmallInteger, default = ROLE_USER)
    nombre = db.Column(db.String(64), index = True)
    apellido = db.Column(db.String(64), index = True)
    fechaNacimiento = db.Column(db.Date(), index = True)
    direccion = db.Column(db.String(64), index = True)
    headshot = db.Column(db.String(255), index = True)
    image_url = db.Column(db.String(255), index = False)
    external_id = db.Column(db.String(255), index = True)
    auth_provider_id = db.Column(db.Integer, ForeignKey('auth_provider.id'))
	
    grupos = db.relationship("Grupo",secondary="userGroups",backref="user")
    deportes = db.relationship("Deportes",secondary="userDeporte",backref="user")
    actividades = db.relationship("UserActivity",backref="user")
    competencias = db.relationship("Competencias",secondary="usuario_competencia",backref="user")
	
    __table_args__ = (UniqueConstraint("external_id", "auth_provider_id", name="unique_user_provider"),)

    def __repr__(self):
        return '<User %r>' % (self.nickname)

    def is_authenticated(self):
        return True

    def is_anonymous(self):
        return False

    def is_active(self):
        return True

    def get_id(self):
        return unicode(str(self.id))
		
    def get_apodo(self):
	    return (self.apodo)
		
    def get_nombre(self):
        return (self.nombre)
		
    def get_apellido(self):
        return (self.apellido)
		
    def get_email(self):
        return (self.email)
		
    def get_direccion(self):
        return (self.direccion)

    def get_fechaNacimiento(self):
        return (self.fechaNacimiento)

    def get_external_id(self):
        return (self.external_id)

    def get_auth_provider_id(self):
        return unicode(str(self.auth_provider_id))

    def save(self):
        self.id = self.col.insert(self.dic)
        print "Debug:" + str(self.id)


friend_list = Table('friend_list', db.metadata,
    Column('list_id', db.Integer, ForeignKey('list.id', ondelete='CASCADE'), primary_key=True, nullable = False),
    Column('friend_id', db.Integer, ForeignKey('friend.id', ondelete='CASCADE'), primary_key=True, nullable = False)
)

class List(db.Model):
	__tablename__ = 'list'

	id = db.Column(db.Integer, primary_key = True)
	nombre = db.Column(db.String(64), index = False, nullable = False)

	def __init__(self, listId, nombre):
		self.id = listId
		self.nombre = nombre
	
	def __repr__(self):
		return "<List('%i','%s')>" % (self.id, self.nombre)

	def save(self):
		self.id = self.col.insert(self.dic)
		print "Debug:" + str(self.id)


class Friend(db.Model):
	__tablename__ = 'friend'

	id = db.Column(db.Integer, primary_key = True)
	nombre = db.Column(db.String(64), index = False, nullable = False)
	image_url = db.Column(db.String(255), index = False)
	external_id = db.Column(db.String(255), index = True, nullable = False)
	auth_provider_id = db.Column(db.Integer, ForeignKey('auth_provider.id', ondelete='CASCADE'), nullable = False)
	user_id = db.Column(db.Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable = False)

	lists = db.relationship("List",secondary=friend_list)
	
	# TODO pasar user_id a tabla de asociacion
	__table_args__ = (UniqueConstraint("external_id", "auth_provider_id","user_id", name="unique_user_provider"),)

	def __repr__(self):
		return "<Friend('%s','%s','%s','%s','%s')>" % (str(self.id), self.nombre, self.external_id, str(self.auth_provider_id),str(self.user_id))
	
	def _find_or_add_list(self, listId):
		q = List.query.filter_by(id=listid)
		t = q.first()
		if not(t):
			raise Exception('La lista '+listId+' no existe')
		return t
	
	def _set_list(self, value):
		# add new tags
		for listId in value:
			self.lists.append(self._find_or_add_list(listId))
	
	def save(self):
		self.id = self.col.insert(self.dic)
		print "Debug:" + str(self.id)


class Grupo(db.Model):
    
    __tablename__ = 'grupos'
    
    id = db.Column(db.Integer, primary_key = True)
    nombre = db.Column(db.String(64), index = True, unique = True)
    puntaje = db.Column(db.Integer, index = True)
    ranking = db.Column(db.Integer, index = True)


    def save(self):
        self.id = self.col.insert(self.dic)
        print "Debug:" + str(self.id)


#Tabla relacion ente grupo y user
usuarios_grupos = db.Table('userGroups', db.Model.metadata,
    Column('user_id', db.Integer, ForeignKey('users.id')),
    Column('grupo_id', db.Integer, ForeignKey('grupos.id'))
)

class Deportes(db.Model):

    __tablename__ = 'deporte'
	
    id = db.Column(db.Integer, primary_key = True)
    nombre = db.Column(db.String(64), index = True, unique = True)
    caloriasHora = db.Column(db.Integer)
	
    def save(self):
        self.id = self.col.insert(self.dic)
        print "Debug:" + str(self.id)

    def __repr__(self):
        return '<User %r>' % (self.nombre)
   
    def __str__(self):
        return (self.nombre)

		
#Tabla relacion ente user y deportes
usuarios_deportes = db.Table('userDeporte', db.Model.metadata,
    Column('user_id', db.Integer, ForeignKey('users.id')),
    Column('deporte_id', db.Integer, ForeignKey('deporte.id'))
)


class UserActivity(db.Model):

    __tablename__ = 'usuario_actividad'
    
    id = db.Column(db.Integer, primary_key = True)
    deporte_id = db.Column('deporte_id', db.Integer, ForeignKey('deporte.id'))
    user_id = db.Column('user_id', db.Integer, ForeignKey('users.id'))
    duracion = db.Column(db.Numeric(6,2), index = True)
    distancia = db.Column(db.Numeric(6,2), index = True)
    fecha = db.Column(db.Date(), index = True)
    
    def save(self):
        self.id = self.col.insert(self.dic)
        print "Debug:" + str(self.id)


class UserActivityWithSensor(db.Model):

    __tablename__ = 'usuario_actividad_with_sensor'
    
    id = db.Column(db.Integer, primary_key = True)
    deporte_id = db.Column('deporte_id', db.Integer, ForeignKey('deporte.id'))
    user_id = db.Column('user_id', db.Integer, ForeignKey('users.id'))
    useractivity_id = db.Column('useractivity_id', db.Integer, ForeignKey('usuario_actividad.id'))
    lat = db.Column("lat", db.Numeric(7,5), primary_key=True)
    lon = db.Column("lon", db.Numeric(8,5), primary_key=True)
    speed =  db.Column("speed", db.Numeric(4,2), primary_key=True)
    time = db.Column(db.String(255), index = True)
    
    def save(self):
        self.id = self.col.insert(self.dic)
        print "Debug:" + str(self.id)

#Tabla relacion ente user y actividad
#usuarios_actividades = db.Table('userActividad', db.Model.metadata,
#    Column('user_id', db.Integer, ForeignKey('users.id')),
#    Column('usuario_actividad_id', db.Integer, ForeignKey('usuario_actividad.id'))
#)

class Competencias(db.Model):

    __tablename__ = 'competencia'

    id = db.Column(db.Integer, primary_key = True)
    nombre = db.Column(db.String(100), unique = True)
    introduccion = db.Column(db.String(500))
    fecha = db.Column(db.Date(), index = True)
    deporte_id = db.Column('deporte_id', db.Integer, ForeignKey('deporte.id'))

    def save(self):
        self.id = self.col.insert(self.dic)
        print "Debug:" + str(self.id)

    def __repr__(self):
        return '<User %r>' % (self.nombre)
   
    def __str__(self):
        return (self.nombre)

#Tabla relacion ente user y deportes
UserCompetition = db.Table('usuario_competencia', db.Model.metadata,
    Column('user_id', db.Integer, ForeignKey('users.id')),
    Column('competencia_id', db.Integer, ForeignKey('competencia.id'))
)

#class UserCompetition(db.Model):
#
#    __tablename__ = 'usuario_competencia'
#
#    id = db.Column(db.Integer, primary_key = True)
#    user_id = db.Column('user_id', db.Integer, ForeignKey('users.id'))
#    competencia_id = db.Column('competencia_id', db.Integer, ForeignKey('competencia.id'))
#
#    def save(self):
#        self.id = self.col.insert(self.dic)
#        print "Debug:" + str(self.id)

